package config;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;

import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;

import org.w3c.dom.CharacterData;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

public class ConfigSection {
	
	private String body;
	private Properties attributes;
	
	private Node node;
	private Object parentNode;
	private XPath xpath;
	
	
	public ConfigSection(XPath xpath,Object parentNode){		
		this.parentNode = parentNode;
		this.xpath = xpath;
	}
	
	public void parse(String express){
		try {
			this.node = (Node)xpath.evaluate(express, parentNode,XPathConstants.NODE);
		} catch (XPathExpressionException e) {
			throw new RuntimeException(e);
		}
		this.body = this.parseBody(this.node);
		this.attributes = this.parseAttribute(this.node);
	}
	
	public List<ConfigSection> getChildSection(){
		List<ConfigSection> sections = new ArrayList<ConfigSection>();
		NodeList children = node.getChildNodes();
		
		for(int i = 0; i < children.getLength(); i++){
			Node child = children.item(i);
			if(child.getNodeType() == Node.ELEMENT_NODE){
				ConfigSection s = new ConfigSection(xpath, node);
				s.body = this.parseBody(child);
				s.attributes = this.parseAttribute(child);
				sections.add(s);
			}
		}
		
		return sections;
	}
	
	public String getBody(){
		return this.body;
	}
	
	public Properties getAttributes(){
		return this.attributes;
	}
	
	public Node getNode(){
		return this.node;
	}
	
	private String parseBody(Node node){
		String body = null;
		NodeList children = node.getChildNodes();
	      for(int i = 0; i<children.getLength();i++){
	    	  Node child = children.item(i);
	    	  if(child.getNodeType() == Node.CDATA_SECTION_NODE){
	    		 body = ((CharacterData)child).getData();
	    		 if(body != null){
	    			 break;
	    		 }
	    	  }
	      }
	      return body;
	}
	
	private Properties parseAttribute(Node node){
		Properties attributes = new Properties();
		NamedNodeMap map = node.getAttributes();
		if(map != null){
			for(int i = 0; i < map.getLength() ;  i++){
				attributes.put(map.item(i).getNodeName(), map.item(i).getNodeValue());
			}
		}
		return attributes;
	}
}
